package com.example.videoplayer


import android.graphics.drawable.AnimationDrawable
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Environment
import android.os.Environment.getExternalStoragePublicDirectory
import android.telephony.TelephonyManager
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity

import com.bumptech.glide.Glide
import com.example.videoplayer.databinding.ActivityMainBinding
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import android.content.Context
import android.os.PowerManager


import androidx.annotation.RequiresPermission
class MainActivity : AppCompatActivity() {
    private var sosShow=false
    private var webSocketManager = WebSocketManager()
    data class VideoObj(val url: String, val type: String)
    data class FileObj(val name: String, val url: String)

    private lateinit var countDownTimer: CountDownTimer
    private lateinit var binding: ActivityMainBinding
    private var mediaPlayer: MediaPlayer? = null
    private var videoFiles:MutableList<VideoObj> = mutableListOf()
    var counter = 0

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
        val deviceId: String? = "867523073582234"
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            telephonyManager.getImei(0) // 获取IMEI号
//        } else {
//            @Suppress("DEPRECATION")
//            telephonyManager.deviceId // 获取设备ID
//        }
        Log.d("sssssssss2", deviceId ?: "")
        val imeiView = binding.imei
        Log.d("sssssssss22", deviceId ?: "")
        imeiView.text = "设备编号 NO$deviceId"

        val isNetworkAvailable = NetworkUtils.isNetworkAvailable(this)
        if (isNetworkAvailable) {
            getUser( deviceId?:"")
        }
        initPlay()
    }

    override fun onStart() {
        sosShow=false
        super.onStart()
        playMedia()
        initMusic()
    }

    override fun onStop() {
        Log.d("sssss3","222")
        val powerManager = applicationContext .getSystemService(Context.POWER_SERVICE) as PowerManager

        if (powerManager.isInteractive) {
            Log.d("liangp","亮屏")
        }

            countDownTimer.cancel()
        if (mediaPlayer != null) {
            mediaPlayer!!.release()
            mediaPlayer = null
        }
        Log.d("sssss3","333")
        super.onStop()
    }
    override fun onDestroy() {
        countDownTimer.cancel()
//        webSocketManager.close()
        if (mediaPlayer != null) {
            mediaPlayer!!.release()
            mediaPlayer = null
        }
        super.onDestroy()
    }
    override fun onResume() {
        super.onResume()
        Log.d("MainActivity", "onResume called")
    }
    private fun getUser(imei: String){
        val clientNumber="ZZ79157976"    //ZZ66686016,hnswsjkj账户  ZZ79157976,test2023账户
        Thread {
            val postResponse = NetworkTask.sendPostRequest(
                "https://www.aed.net.cn/detection/android-video-device/third-party/register",
                "{\"clientNumber\":\"${clientNumber}\",\"deviceNum\":\"${imei}\"}"
            )
            Log.d("remark", postResponse.toString())
            if ( postResponse.has("data")) {
                val data=postResponse.getJSONObject("data")
                if (data.has("remark") && data.isNull("remark")){
                    NetworkTask.sendPutRequest(
                        "https://www.aed.net.cn/detection/android-video-device/edit-remark",
                        "{\"remark\":\"联网${clientNumber}\",\"deviceNum\":\"${imei}\"}"
                    )
                }
            }
            val getResponse = NetworkTask.sendGetRequest("https://www.aed.net.cn/detection/android-video-device/get-play-list?deviceNum=${imei}")
            processJsonAndManageFiles(getResponse)
    var num=0
            webSocketManager.start(
                "wss://www.aed.net.cn/detection/websocket/message/${imei}"//www.aed.net.cn/detection/websocket/message/
            ) { message -> // 这里处理收到的消息
                val jsonObject = JSONObject(message)
                val type: Int = jsonObject.getInt("type")
                val value: String = jsonObject.getString("value")
                Log.d("ssss",value)
                num=num+1
                Log.d("ssss",num.toString())
                if(num==10){
                    turnScreenOff(this)
                }

                if(type==2 && value== "CLOSE_QRCODE"){
                    sosShow=false
                    closeSos()
                    val jsonString = "{\"type\":2,\"value\":\"RESPONDER_SUCCESS\"}"
                    webSocketManager.sendMessage(jsonString)
                }else{
                    if(!sosShow){
                        sosShow=true
                        openSos(value)
                    }

                }
            }
        }.start()

    }
    fun turnScreenOff(context: Context) {
        val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        val wakeLock = powerManager.newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
            "ScreenUtils:WakeLock"
        )
        wakeLock.acquire()
        wakeLock.release()
    }
    private  fun openSos(url: String){
        runOnUiThread { // 在UI线程上更新视图
            playMusic()
            val myVideo=binding.myVideo
            val imageView=binding.imageView
            val imeiView = binding.imei
            val layoutBgView=binding.linearLayout
            val qr=binding.qr
            layoutBgView.visibility = View.VISIBLE
            imeiView.visibility = View.GONE
            myVideo.visibility = View.GONE
            imageView.visibility = View.GONE
            Glide.with(this).load(url).into(qr)
            qr.visibility = View.VISIBLE
            val sosView=binding.sos
            val animation = AnimationUtils.loadAnimation(this, R.anim.zoom_in_out)
            sosView.startAnimation(animation)
            layoutBgView.setBackgroundResource(R.drawable.rotating_background)
            val animationDrawable = layoutBgView.background as AnimationDrawable
            animationDrawable.start()
        }
    }
    private  fun closeSos(){
        runOnUiThread { // 在UI线程上更新视图
            val myVideo=binding.myVideo
            val imageView=binding.imageView
            val imeiView = binding.imei
            val layoutBgView=binding.linearLayout
            val qr=binding.qr
            layoutBgView.visibility = View.GONE
            imeiView.visibility = View.VISIBLE
            myVideo.visibility = View.VISIBLE
            imageView.visibility = View.VISIBLE
            qr.visibility = View.VISIBLE
            qr.visibility = View.GONE
            pauseMusic()
            playMedia()
        }
    }
    private fun initPlay(){
        val picturesDirectory = Environment.getExternalStorageDirectory() // 创建自定义文件夹的路径
        val customFolder = File(picturesDirectory, "video")
        videoFiles=  getVideoList(getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(),customFolder.toString())
        val videoView = binding.myVideo
        videoView.setOnCompletionListener {
            val length = videoFiles.size
            if(counter==length-1){
                counter=0
            }else{
                counter++
            }
            playMedia()
         }
    }
    private fun playMedia(){
        val videoView = binding.myVideo
        val imageView=binding.imageView
        val imeiView = binding.imei
        val length = videoFiles.size
        if(length==0)return
        val ( url,type )=videoFiles[counter]
        imeiView.visibility = View.VISIBLE
        if(type=="video"){
            imageView.visibility = View.GONE
            videoView.visibility = View.VISIBLE
            videoView.setVideoURI(Uri.parse(url))
            videoView.start()
        }else{
            videoView.visibility = View.GONE
            imageView.visibility = View.VISIBLE
            imageView.setImageURI(Uri.parse(url))
            countDownTimer = object : CountDownTimer(15000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    // 每秒钟调用一次
                }
                override fun onFinish() {
                    // 计时结束时隐藏图片
                    Log.d("asd", "结束")
                    @Suppress("NAME_SHADOWING")
                    val length: Int = videoFiles.size
                    if(counter==length-1){
                        counter=0
                    }else{
                        counter++
                    }
                    playMedia()
                    countDownTimer.cancel()
                }
            }.start() // 开始计时

        }
    }
    private fun getVideoList(folderPath: String,folderPath1: String): MutableList<VideoObj> {
        val folder = File(folderPath)
        val folder1 = File(folderPath1)
        val files: Array<File>? = folder.listFiles()
        val files1: Array<File>? = folder1.listFiles()
        val allFiles = (files1?.toList() ?: emptyList()) + (files?.toList() ?: emptyList())

        val videoFiles: MutableList<VideoObj> = mutableListOf()
        allFiles.forEach { file ->
            if (file.isFile && isFileType(file.absolutePath)=="video") {
                videoFiles.add(VideoObj(url = file.absolutePath, type = "video"))
            }
            if (file.isFile && isFileType(file.absolutePath)=="image") {
                videoFiles.add(VideoObj(url = file.absolutePath, type = "image"))
            }
        }
//        println("视频文件列表的长度为：$videoFiles")
        return videoFiles
    }
    private fun initMusic() {
        mediaPlayer = MediaPlayer.create(this, R.raw.sosa)

    }
    // 播放音乐
    private fun playMusic() {
        mediaPlayer?.isLooping = true
        mediaPlayer?.start()
    }

    // 暂停音乐
    private fun pauseMusic() {
        mediaPlayer?.pause()
    }

    private fun isFileType(filePath: String): String {
        val imageExtensions = listOf("jpg", "jpeg", "png")
        val videoExtensions = listOf("mp4","avi")
        val extension = File(filePath).extension.lowercase()
        return when {
            imageExtensions.contains(extension) -> "image"
            videoExtensions.contains(extension) -> "video"
            else -> "unknown"
        }
    }
    private fun processJsonAndManageFiles(getResponse: JSONObject) {
        if (getResponse.has("data") && getResponse.getJSONArray("data").length() > 0) {
            val convertedData = convertData(getResponse.getJSONArray("data"))
            cleanUpFiles(convertedData)
            val downloader = FileDownloader(this)
            downloader.downloadFiles(convertedData){
                initPlay()
            }
        } else {
            deleteAllFiles()
            initPlay()
        }
    }
    private fun convertData(dataArray: JSONArray): List<FileObj> {
        val convertedData = mutableListOf<FileObj>()
        for (i in 0 until dataArray.length()) {
            val dataObject = dataArray.getJSONObject(i)
            val name = dataObject.getString("id")
            val url = dataObject.getString("mediaUrl")
            convertedData.add(FileObj(name, url))
        }
        return convertedData
    }

    private fun cleanUpFiles(fileDataList: List<FileObj>) {
        val downloadsDir = File(getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)
        if (downloadsDir.exists()) {
            val files = downloadsDir.listFiles()
            files?.forEach { file ->
                val exists = fileDataList.any { it.name == file.nameWithoutExtension }
                if (exists) {
                    Log.d("file", "存在")
                } else {
                    Log.d("file", "不存在")
                    file.delete()
                }
            }
        }
    }

    private fun deleteAllFiles() {
        val downloadsDir = File(getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)
        if (downloadsDir.exists()) {
            val files = downloadsDir.listFiles()
            files?.forEach { file ->
                if (file.isFile) {
                    val deleted = file.delete()
                    if (deleted) {
                        println("${file.name} deleted successfully.")
                    } else {
                        println("Failed to delete ${file.name}.")
                    }
                }
            }
        } else {
            println("Downloads directory does not exist.")
        }
    }

}
